package com.idea.dsl.controller;

import com.idea.dsl.client.ModelClientFactory;
import com.idea.dsl.model.DslRequest;
import com.idea.dsl.model.DslResponse;
import com.idea.dsl.service.DslGeneratorService;
import com.idea.dsl.validator.DslValidatorFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DSL生成控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/dsl")
@RequiredArgsConstructor
@Validated
public class DslController {
    
    private final DslGeneratorService dslGeneratorService;
    private final ModelClientFactory modelClientFactory;
    private final DslValidatorFactory validatorFactory;
    
    /**
     * 生成DSL
     */
    @PostMapping("/generate")
    public ResponseEntity<DslResponse> generateDsl(@Valid @RequestBody DslRequest request) {
        log.info("收到DSL生成请求: dslType={}, model={}", request.getDslType(), request.getModel());
        
        try {
            DslResponse response = dslGeneratorService.generateDsl(request);
            return ResponseEntity.ok(response);
            
        } catch (IllegalArgumentException e) {
            log.warn("请求参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(DslResponse.builder()
                            .status(DslResponse.GenerationStatus.FAILED)
                            .errorMessage(e.getMessage())
                            .build());
                            
        } catch (Exception e) {
            log.error("DSL生成异常", e);
            return ResponseEntity.internalServerError()
                    .body(DslResponse.builder()
                            .status(DslResponse.GenerationStatus.FAILED)
                            .errorMessage("服务器内部错误: " + e.getMessage())
                            .build());
        }
    }
    
    /**
     * 获取支持的模型列表
     */
    @GetMapping("/models")
    public ResponseEntity<Map<String, Object>> getSupportedModels() {
        try {
            List<String> availableModels = modelClientFactory.getAvailableClientTypes();
            
            Map<String, Object> result = new HashMap<>();
            result.put("models", availableModels);
            result.put("count", availableModels.size());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("获取支持的模型列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取支持的DSL类型列表
     */
    @GetMapping("/types")
    public ResponseEntity<Map<String, Object>> getSupportedDslTypes() {
        try {
            List<String> supportedTypes = validatorFactory.getSupportedDslTypes();
            
            Map<String, Object> result = new HashMap<>();
            result.put("types", supportedTypes);
            result.put("count", supportedTypes.size());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("获取支持的DSL类型列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("timestamp", System.currentTimeMillis());
        
        try {
            List<String> availableModels = modelClientFactory.getAvailableClientTypes();
            result.put("availableModels", availableModels);
            result.put("modelCount", availableModels.size());
            
            List<String> supportedTypes = validatorFactory.getSupportedDslTypes();
            result.put("supportedDslTypes", supportedTypes);
            result.put("dslTypeCount", supportedTypes.size());
            
        } catch (Exception e) {
            log.warn("健康检查获取详细信息失败", e);
        }
        
        return ResponseEntity.ok(result);
    }
}
